package com.gz.purchase.app;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gz.purchase.R;
import com.gz.purchase.event.EventCode;
import com.gz.purchase.event.MyEvent;
import com.gz.purchase.library.IAuthor;
import com.gz.purchase.library.IOrder;
import com.gz.purchase.library.listener.SubmitOrderListener;
import com.gz.purchase.library.pojo.ProductInfo;
import com.gz.purchase.library.pojo.UserInfo;
import com.gz.purchase.library.util.Constants;
import com.gz.purchase.library.util.PreferenceModel;
import com.gz.purchase.library.util.Tools;
import com.gz.purchase.util.ToastUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 代购下单
 * author wanner1991
 */
public class SubmitOrderActivity extends BaseActivity implements View.OnClickListener {
    private ImageView iv_actionbar_up;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;
    private TextView tv_should_get_money; // 应收
    private EditText tv_reality_get_money;//实际收款
    private EditText et_notes;//备注
    private Button bt_buy;
    private LinearLayout layout_product_item;
    private UserInfo info ;
    private List<ProductInfo> selectedProducts;
    private DisplayImageOptions options;
    private MySubmitOrderListener mySubmitOrderListener;
    private Dialog mLoadingData;
    private double should_pay = 0;//应收款


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_order);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        mActionBar.setCustomView(R.layout.common_activity_head_layout);//自定义ActionBar布局
        initView();
        initListener();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mySubmitOrderListener.release();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.bt_buy){

            if (TextUtils.isEmpty(tv_reality_get_money.getText().toString().trim())){
                ToastUtils.showToast(this,"请输入实收款");
                return ;
            }

            mLoadingData.show();
            JSONArray jsonArray = new JSONArray();
            double reality_pay= 0;
            String contents = "";
            String ssn_note = null;
            // 拼接json字符串
            for (int i = 0 ; i < selectedProducts.size() ; i++){
                ProductInfo info = selectedProducts.get(i);
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("product_id",info.getProduct_id());
                    jsonObject.put("product_num",info.getSelectNum());
                    jsonObject.put("order_price",info.getProduct_price());
                    jsonObject.put("shop_id",info.getShop_id());
                    jsonObject.put("supply_price",info.getSupply_price());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                jsonArray.put(jsonObject);
            }
            contents = Tools.Base64Encode(jsonArray.toString());
            reality_pay = Double.valueOf(tv_reality_get_money.getText().toString().trim());
            ssn_note = et_notes.getText().toString().trim();
            IOrder.getInstance().submitOrder(contents,reality_pay,should_pay,ssn_note,mySubmitOrderListener);

        }else if(view.getId() == R.id.iv_actionbar_up){
            finish();
        }

    }

    private void initView(){
        selectedProducts = (List<ProductInfo>) getIntent().getSerializableExtra("selectedProducts");
        info = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        iv_actionbar_up = (ImageView) this.findViewById(R.id.iv_actionbar_up);
        tv_actionbar_title = (TextView) this.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) this.findViewById(R.id.tv_actionbar_deliveryName);
        tv_should_get_money = (TextView) this.findViewById(R.id.tv_should_get_money);
        tv_reality_get_money = (EditText) this.findViewById(R.id.tv_reality_get_money);
        et_notes = (EditText) this.findViewById(R.id.et_notes);
        bt_buy = (Button) this.findViewById(R.id.bt_buy);
        layout_product_item = (LinearLayout) this.findViewById(R.id.layout_product_item);

        mLoadingData = new Dialog(this,R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);
    }

    private void initListener(){
        iv_actionbar_up.setOnClickListener(this);
        bt_buy.setOnClickListener(this);
        mySubmitOrderListener = new MySubmitOrderListener(this);
    }

    private void initData(){

        tv_actionbar_title.setText("代购下单");
        if (info != null){
            tv_actionbar_deliveryName.setText(info.getName() + "：" + info.getUser_name());
        }
        options = buildOptions();
        // 设置应收款
        for (int i = 0 ; i < selectedProducts.size() ; i++){
            should_pay += selectedProducts.get(i).getProduct_price()*selectedProducts.get(i).getSelectNum();
        }
        tv_should_get_money.setText("￥"+should_pay);
        // 初始化商品条目
        initProductItemLayout();
    }

    private DisplayImageOptions buildOptions() {
        return new DisplayImageOptions.Builder()
                .resetViewBeforeLoading()
                .bitmapConfig(Bitmap.Config.ARGB_8888)
                .cacheInMemory()
                .cacheOnDisc()
                .showStubImage(R.drawable.drawable_recent_white)
                .showImageOnFail(R.drawable.drawable_recent_white)
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
                .displayer(new RoundedBitmapDisplayer(5))
                .build();
    }
    // 初始化商品列表界面，动态生成商品条目
    private void initProductItemLayout(){

        layout_product_item.removeAllViews();
        for (int i = 0 ; selectedProducts != null && i < selectedProducts.size() ; i++){
            ProductInfo info = selectedProducts.get(i);
            View root = LayoutInflater.from(this).inflate(R.layout.submit_order_activity_item,null);
            ImageView iv_product_pic  = (ImageView) root.findViewById(R.id.iv_product_pic);
            TextView tv_product_name = (TextView) root.findViewById(R.id.tv_product_name);
            TextView tv_price_price = (TextView) root.findViewById(R.id.tv_price_price);
            TextView tv_product_num = (TextView) root.findViewById(R.id.tv_product_num);
            TextView tv_buy_num = (TextView) root.findViewById(R.id.tv_buy_num);

            ImageLoader.getInstance().displayImage(info.getPic_url(),iv_product_pic, options);
            tv_product_name.setText(info.getProduct_name());
            tv_price_price.setText("￥" + info.getProduct_price());
            tv_product_num.setText("剩余：" + info.getProduct_num());
            tv_buy_num.setText("×"+info.getSelectNum());

            layout_product_item.addView(root);
        }

    }


    private static class MySubmitOrderListener extends SubmitOrderListener {
        private SubmitOrderActivity mOuter;

        public MySubmitOrderListener(SubmitOrderActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<SubmitOrderActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter,"提交订单成功");
            // 发送广播，通知首页刷新界面，且这一次刷新界面不保留上一次的选中状态！
            Intent brocastIntent = new Intent(Define.ACTION_REFRESH_HOME);
            brocastIntent.putExtra("isReceiveBrocast",true);

            // 使用事件总线，通知代购订单页面刷新数据
            EventBus.getDefault().post(new MyEvent(EventCode.REFRESH));
            mOuter.sendBroadcast(brocastIntent);
            mOuter.finish();

        }

        /**
         * 提交订单后，如果发现库存量不足（可能是有多个代购员同时下单，一个代购员先提交订单，后台数据更新了，而里另一个代购员提交后发现存库不足）
         * @param productsName
         */
        @Override
        public void onUnderstock(String productsName) {
            mOuter.mLoadingData.dismiss();;
            ToastUtils.showToast(mOuter,productsName+"库存量不足");
            // 发送广播，通知首页刷新界面，且这一次刷新界面不保留上一次的选中状态！
            Intent brocastIntent = new Intent(Define.ACTION_REFRESH_HOME);
            brocastIntent.putExtra("isReceiveBrocast", true);
            mOuter.sendBroadcast(brocastIntent);
        }


        @Override
        public void onNoNetWork() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter, Define.MSG_TOAST_NO_NETWORK);
        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter,"提交订单失败");


        }
    }
}
